<?php

namespace app\api\controller;
use app\admin\model\Campaign;
use app\admin\model\CampaignData;
use app\admin\model\CampaignLog;
use app\admin\model\ChildVote;
use app\admin\model\ChildVoteLog;
use app\common\controller\Api;
use app\common\model\Collect;
use app\common\model\CollectBack;
use think\Db;

/**
 * 首页接口
 */
class Vote extends Api
{
    protected $noNeedLogin = ['voteList','collectDetail','collectBack','collect'];
    protected $noNeedRight = ['*'];
    protected $noNeedSite  = ['campaignVote','deliberateVote','activeVoteDetail','votePersonList','collectPerson','collect','collectBack','collectDetail','collectPerson'];
    protected $noNeedCheck = [''];

    /**
     * Notes: 投票列表
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/6/26 0026
     * Time: 15:58
     */
    public function voteList(){
        $site_id = input('site_id');
        $user_id = $this->user_id;;
        $type = input('type',0);
        $keywords = input('keywords');
        $limit = input('limit');
        $order = "createtime desc";
        $where=[];
        $where['publishdata'] = '1';
        $where['status'] = '1';
        if(!empty($keywords)){
            $where['title'] = ['like','%'.$keywords.'%'];
        }
        if(isInt($site_id,1)){
            $where['site_id'] = $site_id;
        }else{
            $this->error('请选择站点');
        }
        if($type)$where['typedata'] = $type;
        $field="*,
            (select count(id) from hawk_child_vote_log where user_id=".$user_id." and vote_id=hawk_vote.id) as deliberate,
            (select count(id) from hawk_campaign_log where user_id=".$user_id." and vote_id=hawk_vote.id and status=1) as campaign";
        $voteModel = new \app\admin\model\Vote();
        $askingData = $voteModel
            ->field($field)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $this->success('成功',$askingData);
    }

    /**
     * Notes: 个人中心投票列表
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/7/23 0023
     * Time: 10:17
     */
    public function votePersonList(){
        $user_id = $this->user_id;;
        $type = input('type',0);
        $keywords = input('keywords');
        $limit = input('limit',15);
        $order = "createtime desc";
        $where=[];
        $where['status'] = '1';
        if(!empty($keywords)){
            $where['title'] = ['like','%'.$keywords.'%'];
        }
        $where['user_id'] = $user_id;
        if($type)$where['typedata'] = $type;
        $field="*";
        $voteModel = new \app\common\model\Vote();
        $askingData = $voteModel->_list($field,$where,$limit,$order);
        $this->success('成功',$askingData);
    }

    /**
     * Notes: 竞选详情
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/6/26 0026
     * Time: 17:12
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function campaignVote(){
        $vote_id = input('vote_id');
        $user_id = $this->user_id;;
        if(empty($vote_id))$this->error('请选择投票事项');
        $campaignModel = new Campaign();
        $voteModel = new \app\admin\model\Vote();
        $voteModel->where('id',$vote_id)->setInc('browse');
        $voteData = $voteModel->where('id',$vote_id)->where('typedata','1')->where('publishdata','1')->find();
        if(empty($voteData))$this->error('无此投票事项');
        $where['vote_id'] = $vote_id;
        $order = "name";
        $field="*,
        (select count(id) from hawk_campaign_log where vote_id=".$vote_id." and status='1' and user_id=".$user_id." and campaign_id=hawk_campaign.id) as choose";
        $voteData['campaign'] = $campaignModel->field($field)->where($where)->order($order)->select();
        $voteData['choose'] = Db::name('campaign_log')->where($where)->where('user_id',$user_id)->where('status','1')->count('id');
        $this->success('成功',$voteData);
    }

    /**
     * Notes: 评议详情
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/6/28 0028
     * Time: 11:41
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function deliberateVote(){
        $vote_id = input('vote_id');
        $user_id = $this->user_id;;
        if(empty($vote_id))$this->error('请选择投票事项');
        $childVoteModel = new ChildVote();
        $voteModel = new \app\admin\model\Vote();
        $voteModel->where('id',$vote_id)->setInc('browse');
        $voteData = $voteModel->where('id',$vote_id)->where('typedata','2')->where('publishdata','1')->find();
        if(empty($voteData))$this->error('无此投票事项');
        $where['vote_id'] = $vote_id;
        $order = "id";
        $field="*,
        (select typedata from hawk_child_vote_log where vote_id=".$vote_id." and user_id=".$user_id." and child_vote_id=hawk_child_vote.id) as typedata";
        $voteData['child_vote']= $childVoteModel->field($field)->where($where)->order($order)->select();
        $this->success('成功',$voteData);
    }

    /**
     * Notes: 竞选投票
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/6/28 0028
     * Time: 14:24
     */
    public function campaignBet(){
        $user_id = $this->user_id;;
        $vote_id = input('vote_id');
        $site_id = input('site_id');
        $campaign_ids = input('campaign_ids');
        if(empty($vote_id))$this->error('投票id不可为空');
        if(empty($campaign_ids))$this->error('请选择至少一个候选人');
        $campaignIdsArr = array_filter(explode(',',$campaign_ids));
        if(empty($campaignIdsArr))$this->error('请选择至少一个候选人');
        $campaignLog = [];
        $vote_limit = Db::name('vote')->where('id',$vote_id)->value('vote_limit');
        if(count($campaignIdsArr)>$vote_limit)$this->error('每人仅可投'.$vote_limit.'票');
        $isBet = Db::name('campaign_log')->where('vote_id',$vote_id)->where('user_id',$user_id)->where('status','1')->count('id');
        if($isBet)$this->error('已投票');
        foreach ($campaignIdsArr as $k=>$v){
            $campaignLog[$k]['user_id'] = $user_id;
            $campaignLog[$k]['vote_id'] = $vote_id;
            $campaignLog[$k]['campaign_id'] = $v;
            $campaignLog[$k]['site_id'] = $site_id;
        }
        if($campaignLog){
            $res = false;
            Db::startTrans();
            try{
                $campaignModel = new Campaign();
                $campaignLogModel = new CampaignLog();
                $campaignModel->where('id','in',$campaignIdsArr)->setInc('vote_numer');
                if($campaignLogModel->saveAll($campaignLog))$res = true;
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->error('失败');
            }
            if($res)$this->success('投票成功');
        }else{
            $this->error('数据错误');
        }
    }

    /**
     * Notes:  评议投票
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/6/28 0028
     * Time: 14:33
     */
    public function deliberateBet(){
        $user_id = $this->user_id;
        $vote_id = input('vote_id');
        $site_id = input('site_id');
        $child_vote_id = input('child_vote_id');
        $typedata = input('typedata');
        if(empty($vote_id))$this->error('投票id不可为空');
        if(empty($child_vote_id) || empty($typedata))$this->error('请投票');
        $childVoteLogModel = new ChildVoteLog();
        $ret = $childVoteLogModel->where('user_id',$user_id)->where('child_vote_id',$child_vote_id)->find();
        if($ret)$this->error('已投票，不可更改');
        if($child_vote_id){
            $res = false;
            Db::startTrans();
            try{
                $childVoteModel = new ChildVote();
                switch ($typedata){
                    case '1':
                        $childVoteModel->where('id',$child_vote_id)->setInc('agree');
                        break;
                    case '2':
                        $childVoteModel->where('id',$child_vote_id)->setInc('against');
                        break;
                    case '3':
                        $childVoteModel->where('id',$child_vote_id)->setInc('notcare');
                        break;
                    default:
                        $this->error();
                }
                $childVoteData['user_id'] = $user_id;
                $childVoteData['vote_id'] = $vote_id;
                $childVoteData['site_id'] = $site_id;
                $childVoteData['child_vote_id'] = $child_vote_id;
                $childVoteData['typedata'] = $typedata;
                if($childVoteLogModel->save($childVoteData))$res = true;
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->error('失败');
            }
            if($res)$this->success('投票成功');
        }else{
            $this->error('数据错误');
        }
    }

    /**
     * Notes: 人员资料库
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/7/8 0008
     * Time: 9:44
     * @throws \think\exception\DbException
     */
    public function campaignData(){
        $site_id = input('site_id');
        $limit = input('limit',15);
        if(empty($site_id))$this->error('请选择站点');
        $where['status'] = 1;
        $where['site_id'] = $site_id;
        $campaignDataModel = new CampaignData();
        $list = $campaignDataModel->where($where)->paginate($limit);
        $this->success('成功',$list);
    }

    /**
     * Notes: 新建参选人员
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/7/3 0003
     * Time: 16:38
     */
    public function campaignAdd(){
        $param = $this->request->post();
        $validate = new \app\api\validate\Campaign();
        if (!$validate->scene('add')->check($param)) {
            $this->error($validate->getError());
        }
        $campaignDataModel = new CampaignData();
        $campaignDataModel->allowField(true)->save($param);
        $id = $campaignDataModel->getLastInsID();
        if($id){
            $this->success('操作成功',['id'=>$id]);
        }else{
            $this->error('添加失败');
        }
    }

    /**
     * Notes: 删除人员资料库
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/7/3 0003
     * Time: 16:43
     */
    public function campaignDelete(){
        $param = $this->request->post();
        if(isset($param['id']) && !empty($param['id'])){
            $where['id'] = $param['id'];
            $campaignDataModel = new CampaignData();
            $campaignDataModel->where($where)->setField('status',0);
            $this->success('操作成功');
        }else{
            $this->error('缺少参数');
        }
    }

    /**
     * Notes: 竞选投票新增
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/7/8 0008
     * Time: 11:57
     */
    public function campaignVoteAdd(){
        $param = $this->request->post();
        $validate = new \app\api\validate\Vote();
        if (!$validate->scene('campaign')->check($param)) {
            $this->error($validate->getError());
        }
        $userInfo = (new \app\common\model\User())->find($param['user_id']);
        $group_name = Db::name('user_group')->where('id',$userInfo->group_id)->value('name');
        $voteData = [
            'user_id'       => $param['user_id'],
            'site_id'       => $param['site_id'],
            'title'         => $param['title'],
            'typedata'      => '1',
            'vote_limit'    => $param['vote_limit'],
            'endtime'       => strtotime($param['endtime']),
            'starttime'     => time(),
            'publishdata'   => '1',
            'status'        => 1,
            'resource'      => $group_name,
        ];
        $where['id']=['in',trim($param['campaign_id'],',')];
        $campaignData = Db::name('campaign_data')->field('site_id,name,age,nation,politic,introduction,avatar,job')->where($where)->select();
        if(empty($campaignData)){
            $this->error('参选人员信息失效，请重新选择');
        }
        Db::startTrans();
        try{
            $voteModel = new \app\admin\model\Vote();
            $voteModel->allowField(true)->save($voteData);
            $vote_id = $voteModel->getLastInsID();
            foreach ($campaignData as $k=>$v){
                $v['vote_id'] = $vote_id;
                $v['user_id'] = $param['user_id'];
                $campaignData[$k]=$v;
            }
            $campaignModel = new Campaign();
            $campaignModel->saveAll($campaignData);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    /**
     * Notes: 评议新增
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/7/8 0008
     * Time: 11:58
     */
    public function childVoteAdd(){
        $param = $this->request->post();
        $validate = new \app\api\validate\Vote();
        if (!$validate->scene('child')->check($param)) {
            $this->error($validate->getError());
        }
        $userInfo = (new \app\common\model\User())->find($param['user_id']);
        $group_name = Db::name('user_group')->where('id',$userInfo->group_id)->value('name');
        $param['content'] = isset($_POST['content'])?$_POST['content']:'';
        $voteData = [
            'user_id'       => $param['user_id'],
            'site_id'       => $param['site_id'],
            'title'         => $param['title'],
            'typedata'      => '2',
            'endtime'       => strtotime($param['endtime']),
            'starttime'     => time(),
            'publishdata'   => '1',
            'status'        => 1,
            'resource'      => $group_name,
        ];
        $childVoteData = $param['child'];
        if(empty($childVoteData)){
            $this->error('请添加评议事件');
        }
        Db::startTrans();
        try{
            $voteModel = new \app\admin\model\Vote();
            $voteModel->allowField(true)->save($voteData);
            $vote_id = $voteModel->getLastInsID();
            foreach ($childVoteData as $k=>$v){
                $v['site_id'] = $param['site_id'];
                $v['vote_id'] = $vote_id;
                $childVoteData[$k] = $v;
            }
            $childVoteModel = new ChildVote();
            $childVoteModel->saveAll($childVoteData);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->error('操作失败:'.$e->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * Notes: 活动新增
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/7/8 0008
     * Time: 14:31
     */
    public function activeVoteAdd(){
        $param = $this->request->post();
        $validate = new \app\api\validate\Vote();
        if (!$validate->scene('active')->check($param)) {
            $this->error($validate->getError());
        }
        $userInfo = (new \app\common\model\User())->find($param['user_id']);
        $group_name = Db::name('user_group')->where('id',$userInfo->group_id)->value('name');
        $param['content'] = $_POST['content'];
        $voteData = [
            'user_id'       => $param['user_id'],
            'site_id'       => $param['site_id'],
            'title'         => $param['title'],
            'typedata'      => '3',
            'endtime'       => strtotime($param['endtime']),
            'starttime'     => time(),
            'publishdata'   => '1',
            'status'        => 1,
            'resource'      => $group_name,
        ];
        Db::startTrans();
        try{
            $voteModel = new \app\admin\model\Vote();
            $voteModel->allowField(true)->save($voteData);
            $vote_id = $voteModel->getLastInsID();
            $childVoteData=[
                'site_id'    => $param['site_id'],
                'vote_id'    => $vote_id,
                'title'      => $param['title'],
                'votecontent'=> $param['content']
            ];
            $childVoteModel = new ChildVote();
            $childVoteModel->save($childVoteData);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->error('操作失败：'.$e->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * Notes: 活动详情
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/7/8 0008
     * Time: 15:11
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function activeVoteDetail(){
        $vote_id = input('vote_id');
        $user_id = $this->user_id;;
        if(empty($vote_id))$this->error('请选择投票事项');
        $childVoteModel = new ChildVote();
        $voteModel = new \app\admin\model\Vote();
        $voteModel->where('id',$vote_id)->setInc('browse');
        $voteData = $voteModel->where('id',$vote_id)->where('typedata','3')->where('publishdata','1')->find();
        if(empty($voteData))$this->error('无此投票事项');
        $where['vote_id'] = $vote_id;
        $order = "id";
        $field="*,
        (select typedata from hawk_child_vote_log where vote_id=".$vote_id." and user_id=".$user_id." and child_vote_id=hawk_child_vote.id) as typedata";
        $voteData['child_vote']= $childVoteModel->field($field)->where($where)->order($order)->find();
        $this->success('成功',$voteData);
    }

    /**
     * Notes: 活动投票
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/7/8 0008
     * Time: 15:45
     */
    public function activeVoteBet(){
        $user_id = $this->user_id;;
        $vote_id = input('vote_id');
        $site_id = input('site_id');
        $child_vote_id = input('child_vote_id');
        $typedata = input('typedata');
        if(empty($vote_id))$this->error('投票id不可为空');
        if(empty($child_vote_id) || empty($typedata))$this->error('请投票');
        $childVoteLogModel = new ChildVoteLog();
        $ret = $childVoteLogModel->where('user_id',$user_id)->where('child_vote_id',$child_vote_id)->find();
        if($ret)$this->error('每人仅可投票一次');
        $childVoteData = [['typedata'=>$typedata,'child_vote_id'=>$child_vote_id]];
        $childVoteUpdate = [];
        if($childVoteData){
            $res = false;
            Db::startTrans();
            try{
                $childVoteModel = new ChildVote();
                foreach ($childVoteData as $k=>$v){
                    $childVoteUpdate[$k]['id'] = $v['child_vote_id'];
                    switch ($v['typedata']){
                        case '1':
                            $childVoteModel->where('id',$v['child_vote_id'])->setInc('agree');
                            break;
                        case '2':
                            $childVoteModel->where('id',$v['child_vote_id'])->setInc('against');
                            break;
                        default:
                            $this->error();
                    }
                    $childVoteData[$k]['user_id'] = $user_id;
                    $childVoteData[$k]['vote_id'] = $vote_id;
                    $childVoteData[$k]['site_id'] = $site_id;
                    $childVoteData[$k]['child_vote_id'] = $v['child_vote_id'];
                    $childVoteData[$k]['typedata'] = $v['typedata'];
                }
                if($childVoteLogModel->saveAll($childVoteData))$res = true;
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->error('失败');
            }
            if($res)$this->success('投票成功');
        }else{
            $this->error('数据错误');
        }
    }

    /**
     * Notes: 暂停投票
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/7/8 0008
     * Time: 16:08
     */
    public function stopVoteBte(){
        $vote_id = input('vote_id');
        $publishdata = input('publishdata');
        if(empty($vote_id))$this->error('投票id不可为空');
        $voteModel = new \app\admin\model\Vote();
        switch ($publishdata){
            case '1':
            case '0':
                $res = $voteModel->where('id',$vote_id)->setField('publishdata',$publishdata);
                break;
            default:
                $this->error('失败');
        }
        if($res)$this->success('操作成功');
        $this->error('操作失败');
    }

    public function collect(){
        $site_id = input('site_id');
        $keywords = input('keywords');
        $limit = input('limit',15);
        $order = "createtime desc";
        $where=[];
        $where['publishdata'] = '1';
        $where['status'] = '1';
        if(!empty($keywords)){
            $where['title'] = ['like','%'.$keywords.'%'];
        }
        if(!empty($site_id)){
            $where['site_id'] = $site_id;
        }
        $field="*";
        $collectModel = new Collect();
        $askingData = $collectModel->_list($field,$where,$limit,$order);
        $this->success('成功',$askingData);
    }

    public function collectPerson(){
        $user_id = $this->user_id;;
        $keywords = input('keywords');
        $limit = input('limit',15);
        $order = "createtime desc";
        $where=[];
        $where['publishdata'] = '1';
        $where['status'] = '1';
        if(!empty($keywords)){
            $where['title'] = ['like','%'.$keywords.'%'];
        }
        $where['user_id'] = $user_id;
        $field="*";
        $collectModel = new Collect();
        $askingData = $collectModel->_list($field,$where,$limit,$order);
        $this->success('成功',$askingData);
    }

    public function collectDetail(){
        $collect_id = input('collect_id');
        if(empty($collect_id))$this->error('请选择征集事件');
        $collectModel = new Collect();
        $detail = $collectModel->find($collect_id);
        $this->success('成功',$detail);
    }
    /**
     * Notes: 征集回复列表
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/7/23 0023
     * Time: 10:40
     */
    public function collectBack(){
        $collect_id = input('collect_id');
        $limit = input('limit',15);
        if(empty($collect_id))$this->error('请选择征集事件');
        $where['collect_id'] = $collect_id;
        $where['status'] = '1';
        $order = "createtime desc";
        $field = "*";
        $collectBackModel = new CollectBack();
        $list = $collectBackModel->_list($field,$where,$limit,$order);
        $this->success('成功',$list);
    }
    /**
     * Notes: 征集回复
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/7/23 0023
     * Time: 11:10
     */
    public function answered(){
        $asking_id = input('collect_id');
        $user_id = $this->user_id;;
        $content = input('content');
        if(empty($asking_id))$this->error('缺少参数');
        if(empty($content))$this->error('请填写回复内容');
        if(mb_strlen($content)>200)$this->error('回复内容不可超过200字');
        $askingBackModel = new \app\admin\model\CollectBack();
        $data=[
            'user_id'=>$user_id,
            'collect_id'=>$asking_id,
            'content'=>$content
        ];
        if($askingBackModel->save($data)){
            $this->success('回复成功');
        }else{
            $this->error('回复失败');
        }
    }
}